<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>{{ $route.query.id ? "试题修改" : "试题录入" }}</span>
        </div>
        <el-form
          label-width="100px"
          ref="formData"
          :model="formData"
          :rules="rules"
        >
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              style="width: 400px"
              v-model="formData.subjectID"
              @change="getTags"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select style="width: 400px" v-model="formData.catalogID">
              <el-option
                v-for="item in catalogueList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select style="width: 400px" v-model="formData.enterpriseID">
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="province">
            <el-select
              style="width: 197px; margin-right: 6px"
              v-model="formData.province"
              @change="getArea"
            >
              <el-option
                v-for="item in cityList"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <el-select style="width: 197px" v-model="formData.city">
              <el-option
                v-for="item in areaList"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select style="width: 400px" v-model="formData.direction">
              <el-option
                v-for="item in directionList"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="formData.questionType" @change="reset">
              <el-radio
                v-for="item in questionType"
                :key="item.value"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="formData.difficulty">
              <el-radio
                v-for="item in difficulty"
                :key="item.value"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <quillEditor
               ref="text"
                read-only
                :options="editorOption"

              @click.native="handleEditAblequestion"
              @blur="$refs.formData.validateField('question')"
              v-model="formData.question"
            ></quillEditor>
          </el-form-item>
          <el-form-item label="选项:" v-if="formData.questionType !== '3'">
            <el-radio-group v-model="radio" @change="Add">
              <div
                v-for="(item, index) in formData.options"
                :key="index"
                class="inputStyle"
              >
                <el-radio
                  :label="item.code"
                  v-if="formData.questionType === '1'"
                  >{{ item.code }}:</el-radio
                >
                <el-checkbox v-else v-model="item.isRight"
                  >{{ item.code }}:</el-checkbox
                >
                <el-input style="width: 250px" v-model="item.title"></el-input>
                <getinfo v-model="item.img"></getinfo>
                <el-button
                type="danger"
                style="margin-left:10px"
                v-if="index===formData.options.length-1 && index > 3"
                @click="Del(index)"
                >删除 </el-button>
              </div>
              <el-button
                type="danger"
                :disabled="formData.questionType !== '2'"
                @click="addOptions"
                >+增加选项与答案</el-button
              >
            </el-radio-group>
          </el-form-item>

          <el-form-item label="解析视频:">
            <el-input
              type="text"
              v-model="formData.videoURL"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <quillEditor
              ref="text1"
              read-only
              :options="editorOption"

              @blur="$refs.formData.validateField('answer')"
              v-model="formData.answer"
              @click.native="handleEditAblequestion1"
            ></quillEditor>
          </el-form-item>
          <el-form-item label="题目备注:">
            <el-input
              clearable
              type="textarea"
              v-model="formData.remarks"
              style="width: 400px"
              rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="试题标签:" prop="tags">
            <el-select
            style="min-width:400px"
              v-model="formData.tags"
              multiple
              filterable
              default-first-option
              placeholder="请选择文章标签"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="$route.query.id" type="success" @click="submject"
              >确认修改</el-button
            >
            <el-button v-else type="primary" @click="submject"
              >确认提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 学科api
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import {
  simple,
  entrepreneurlist,
  tagssimple,
  add,
  catalogueSimple,
  update,
  detail
} from '@/api/hmmm/questionsAdd.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css' // 导入样式
import 'quill/dist/quill.snow.css' // 导入snow样式
import 'quill/dist/quill.bubble.css' //
import Getinfo from './getinfo.vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
export default {
  components: {
    quillEditor,
    Getinfo
  },
  data () {
    return {
      editorOption: {
        modules: {
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },
      qillInit: true,
      letterArr: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      radio: '',
      qillInit1: true,
      formData: {
        // 学科id
        subjectID: '',
        // 目录id
        catalogID: '',
        // 企业id
        enterpriseID: '',
        // 城市id
        province: '',
        // 地区id
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        options: [
          {
            isRight: false,
            code: 'A',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'B',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'C',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'D',
            title: '',
            img: ''
          }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: []
      },
      rules: {
        province: [
          { required: true, message: '请选择地区', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value) {
                this.formData.city
                  ? callback()
                  : callback(new Error('请选择地区'))
              }
            },
            trigger: 'change'
          }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error('请输入题干'))
            },
            trigger: 'blur'
          }
        ],
        tags: [{ required: true, message: '请选择标签', trigger: 'change' }],
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error('请输入答案解析'))
            },
            trigger: 'blur'
          }
        ]
      },

      // 学科列表
      subjectList: [],
      // 目录列表
      catalogueList: [],
      // 标签列表
      tagsList: [],
      // 城市列表
      cityList: [],
      // 地区列表
      areaList: [],
      // 企业列表
      companyList: [],
      // 方向列表
      directionList: direction,
      // 题型多选按钮列表
      questionType: questionType,
      // 难度多选按钮列表
      difficulty: difficulty
    }
  },
  async created () {
    // 获取学科列表
    const res = await simple()
    this.subjectList = res.data
    // 获取企业列表
    const ress = await entrepreneurlist('pagesize=10000')
    this.companyList = ress.data.items
    // 获取城市列表
    this.cityList = await provinces()
    // 获取id之后修改题目

    // 回显发请求
    if (this.$route.query.id) {
      const resss = await detail(this.$route.query.id)
      this.formData = resss.data
      this.formData.tags = this.formData.tags.split(',')
      if (this.formData.questionType === '1') {
        const index = this.formData.options.findIndex(
          (ele) => ele.isRight === 1
        )

        if (index > 0) this.radio = this.formData.options[index].code
      } else if (this.formData.questionType === '2') {
        this.formData.options.forEach((ele) => {
          ele.isRight = !!ele.isRight
        })
      }

      const res = await tagssimple({ subjectID: this.formData.subjectID })

      this.tagsList = res.data
      const ress = await catalogueSimple({
        subjectID: this.formData.subjectID
      })
      this.catalogueList = ress.data
      this.areaList = await citys(this.formData.province)
    }
  },

  mounted () {
    this.$refs.text.quill.enable(false)
    this.$refs.text1.quill.enable(false)
  },
  methods: {
    handleEditAblequestion () {
      if (this.qillInit) {
        this.$refs.text.quill.enable(true)
        this.$refs.text.quill.focus()
        this.qillInit = false
      }
    },
    handleEditAblequestion1 () {
      if (this.qillInit1) {
        this.$refs.text1.quill.enable(true)
        this.$refs.text1.quill.focus()
        this.qillInit1 = false
      }
    },
    async getArea (cityName) {
      // 初始化地区
      this.formData.city = ''
      const res = await citys(cityName)
      this.areaList = res
    },
    // 获取学科对应标签
    async getTags (subjectNumber) {
      const res = await tagssimple({ subjectID: subjectNumber })
      this.formData.tags = ''
      this.tagsList = ''
      this.tagsList = res.data

      const ress = await catalogueSimple({ subjectID: subjectNumber })
      this.formData.catalogID = ''
      this.catalogueList = ''
      this.catalogueList = ress.data
    },
    Add (Num) {
      this.formData.options.forEach((ele) => {
        ele.isRight = false
      })
      this.formData.options.find((ele) => ele.code === Num).isRight = true
    },
    reset () {
      this.formData.options.forEach((ele) => {
        ele.isRight = false
      })
      this.radio = ''
    },
    addOptions () {
      this.formData.options.push({
        isRight: false,
        code: this.letterArr[this.formData.options.length],
        title: '',
        img: ''
      })
    },
    async submject () {
      this.$refs.formData.validate((valid) => {
        valid && this.submission()
      })
    },
    // 清除表单
    clearform () {
      this.$refs.formData.resetFields()
      this.formData.tags = ''
      this.formData.remarks = ''
      this.formData.videoURL = ''
      this.formData.city = ''
      this.catalogueList = ''
      this.tagsList = ''
      this.areaList = ''
      this.radio = ''
      this.formData.options.forEach((ele) => {
        ele.title = ''
      })
    },
    Del (id) {
      console.log(id)
      this.formData.options.splice(id, 1)
    },
    async submission () {
      try {
        if (Array.isArray(this.formData.tags)) {
          this.formData.tags = this.formData.tags.join(',')
        }
        if (this.$route.query.id) {
          await update(this.formData)
          this.clearform()
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        } else {
          await add(this.formData)
          this.clearform()
          this.$message.success('提交成功')
          this.$router.push('/questions/list')
        }
      } finally {
        this.formData.tags = this.formData.tags.split(',')
      }
    }
  },
  watch: {
    $route: {
      deep: true,
      handler (newVal) {
        this.clearform()
        this.$refs.formData.resetFields()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.quill-editor {
  width: 100%;
  height: 250px;
  margin-bottom: 90px;
}

.radion {
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;

}
.inputStyle {
  margin-bottom: 30px;
  display: flex;
  align-items: center;
}
</style>
<style>
.el-checkbox__label {
  margin-right: 30px;
}
</style>
